package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.utils.BaseContext;
import com.itheima.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/22 20:42
 * @Desc: 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到客户端请求...");

        Long employeeId = (Long) request.getSession().getAttribute("employeeId");
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (employeeId != null || userId != null) {
            if (employeeId != null)
                BaseContext.setCurrentId(employeeId);
            if (userId != null)
                BaseContext.setCurrentId(userId);

            log.info("已登录，放行请求...");
            return true;
        }

        log.info("未登录...");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
